#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cgi
import datetime
import wsgiref.handlers
import webapp2
import urllib,urllib2
import jinja2
import os,sys

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import urlfetch


jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))


class OChanBand(db.Model):
  url = db.StringProperty()
  name = db.StringProperty()
  contents = db.StringProperty(multiline=True)
  created = db.DateTimeProperty()
  updated = db.DateTimeProperty(auto_now_add=True)

class OChanOto(db.Model):
  band = db.ReferenceProperty(OChanBand)
  url = db.StringProperty()
  title = db.StringProperty()
  description = db.StringProperty()
  created = db.DateTimeProperty()
  updated = db.DateTimeProperty(auto_now_add=True)




class OChanIndex(webapp2.RequestHandler):
  def get(self):
    template = jinja_environment.get_template('index.html')
    otos = OChanOto().all()
    for i,v in enumerate(otos):
      v['url'] = '/contents?url=' + urllib.quote_plus(v['url'])
    self.response.headers['Content-Type'] = 'text/html'
    self.response.out.write(template.render(otos=otos))

class OChanContents(webapp2.RequestHandler):
  def get(self):
    url = self.request.get('url')
    mp3 = urlfetch.fetch(url)
    self.response.headers['Content-Type'] = mp3.headers['Content-Type']
    self.response.out.write(mp3.content)

class OChanFixture(webapp2.RequestHandler):
  def get(self):
    band = OChanBand(parent=db.Key.from_path('OChanBand','sampler'),
                     url=u'http://oto-channel.appspot.com',
                     name=u'o-chan',
                     contents=u'sample',
                     created=datetime.datetime.now()
                     )
    band.put()
    oto = OChanOto(band=band,
                   url=u'https://docs.google.com/uc?export=download&id=0B2ZAtOzdg6pCOTZlMDk0OTEtM2RiOC00YjZiLTg1ZTctZWY2MGYxZDYyZDA1',
                   title=u'進まない僕',
                   description=u'sample',
                   created=datetime.datetime.now()
                   )
    oto.put()


app = webapp2.WSGIApplication([
  ('/',OChanIndex),
  ('/contents',OChanContents),
  ('/fixture',OChanFixture),
], debug=True)


def main():
  wsgiref.handlers.CGIHandler().run(app)


if __name__ == '__main__':
  main()
